package com.example.demo.service.impl;

import com.example.demo.entity.Bookkeeping;
import com.example.demo.entity.User;
import com.example.demo.repository.BookkeepingRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.BookkeepingService;
import com.example.demo.service.UserService;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class BookkeepingServiceImpl implements BookkeepingService {

    @Autowired
    private BookkeepingRepository bookkeepingRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService; // Assuming UserService has methods like increment/decrementBookCount


    @Override
    @Transactional
    public Bookkeeping addRecord(Integer userId, Bookkeeping record) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new EntityNotFoundException("用户未找到，ID: " + userId));
        record.setUser(user);

        // 确保 bookDate 不为空，以便 prePersistOrUpdate 能正确工作
        if (record.getBookDate() == null) {
            record.setBookDate(LocalDate.now()); // 或者抛出异常，要求必须提供日期
        }
        // prePersistOrUpdate 会自动设置 year 和 month

        Bookkeeping savedRecord = bookkeepingRepository.save(record);
        userService.incrementBookCount(userId); // 增加用户记账数量
        return savedRecord;
    }

    @Override
    public List<Bookkeeping> getRecordsByUserAndMonth(Integer userId, int year, int month) {
        if (!userRepository.existsById(userId)) {
            throw new EntityNotFoundException("用户未找到，ID: " + userId);
        }
        return bookkeepingRepository.findByUserIdAndYearAndMonthOrderByBookDateDesc(userId, year, month);
    }

    @Override
    public Bookkeeping getRecordByIdAndUser(Integer recordId, Integer userId) {
        Bookkeeping record = bookkeepingRepository.findById(recordId)
                .orElseThrow(() -> new EntityNotFoundException("记账记录未找到，ID: " + recordId));
        if (!record.getUser().getId().equals(userId)) {
            throw new SecurityException("无权访问该记账记录"); // 或者更具体的异常
        }
        return record;
    }

    @Override
    @Transactional
    public Bookkeeping updateRecord(Integer recordId, Integer userId, Bookkeeping recordDetails) {
        Bookkeeping existingRecord = getRecordByIdAndUser(recordId, userId); // 校验权限和存在性

        // 更新允许修改的字段
        if (recordDetails.getType() != null) {
            existingRecord.setType(recordDetails.getType());
        }
        if (recordDetails.getBookDate() != null) {
            existingRecord.setBookDate(recordDetails.getBookDate());
        }
        if (recordDetails.getCategory() != null) {
            existingRecord.setCategory(recordDetails.getCategory());
        }
        if (recordDetails.getPrice() != null) {
            existingRecord.setPrice(recordDetails.getPrice());
        }
        if (recordDetails.getRemark() != null) {
            existingRecord.setRemark(recordDetails.getRemark());
        }
        // prePersistOrUpdate 会在保存时更新 year 和 month

        return bookkeepingRepository.save(existingRecord);
    }

    @Override
    @Transactional
    public void deleteRecord(Integer recordId, Integer userId) {
        Bookkeeping recordToDelete = getRecordByIdAndUser(recordId, userId); // 校验权限和存在性
        bookkeepingRepository.delete(recordToDelete);
        userService.decrementBookCount(userId); // 减少用户记账数量
    }

    @Override
    public List<Bookkeeping> getAllRecordsByUserId(Integer userId) { // <--- 新增方法的实现
        if (!userRepository.existsById(userId)) {
            // 或者根据业务需求返回空列表或特定响应
            throw new EntityNotFoundException("用户未找到，ID: " + userId + "，无法查询其账本数据。");
        }
        return bookkeepingRepository.findByUserIdOrderByBookDateDesc(userId);
    }
}
